﻿using System;
using System.Collections.Generic;
using System.Text;

using Kenly.ChineseSegment.DictionaryLoader;
using Kenly.ChineseSegment.DictionaryWriter;

namespace Kenly.ChineseSegment
{
    internal class ForwardSegmentDictionary : SegmentDictionaryBase
    {
       
        /// <summary>
        /// 将分词链表解析到分词字典中。
        /// </summary>
        /// <param name="dictionaryPath"></param>
        /// <param name="loader"></param>
        /// <returns></returns>
        public override bool Parse(List<string> segmentList)
        {
            if (segmentList == null || segmentList.Count <= 0)
            {
                return false;
            }

            base.SegmentList.Clear();
            base.Segments.Clear();

            AddSegmentListToDictionary(segmentList);
            base.SegmentList.AddRange(segmentList);
            return true;
        }

        /// <summary>
        /// 将分词链表追加到分词字典中。
        /// </summary>
        /// <param name="dictionaryPath"></param>
        /// <param name="loader"></param>
        /// <returns></returns>
        public override bool Append(List<string> segmentList)
        {
            if (segmentList == null || segmentList.Count <= 0)
            {
                return false;
            }

            AddSegmentListToDictionary(segmentList);
            base.SegmentList.AddRange(segmentList);
            return true;
        }

        /// <summary>
        /// 将分词列表存于字典中。
        /// </summary>
        /// <param name="segmentList"></param>
        private void AddSegmentListToDictionary(List<string> segmentList)
        {
            foreach (string element in segmentList)
            {
                if (string.IsNullOrEmpty(element) || element.Length<2)
                {
                    continue;
                }

                //分词的第一个字符
                //string firstChar = element.Substring(0, 1);

                //分词的前2个字符
                string startTwoChars = element.Substring(0, 2);

                if (this.Segments.ContainsKey(startTwoChars))
                {
                    this.Segments[startTwoChars].Add(element);
                }
                else
                {
                    List<string> subSegments = new List<string>();
                    subSegments.Add(element);
                    this.Segments.Add(startTwoChars, subSegments);
                }
            }
        }

    }
}
